const jwt:any = require("jsonwebtoken");
const { secret } = require("./tokenSecret");  //秘钥
async function check(ctx, next) {
    let url = ctx.request.url;
    // 登陆 不用检查
    if (url == "/login/signIn") await next();
    else {
        // 规定token写在header 的 'token'
        let token = ctx.request.headers["authorization"];
        // 解码 exp:过期时间,单位s
        await jwt.verify(token,secret,async (err,payload)=>{
            if(err){
                //超时或错误，重新登录
                ctx.body = { success: false, msg: "登录失效，请重新登录", code: 401 };
            }else{
                let nowtime = new Date().getTime()/1000;
                if (nowtime < payload.exp) {
                    //未超时
                    ctx.req.authData = payload;
                    ctx.request.authData = payload;
                    await next();
                } else {
                    //超时
                    ctx.body = { success: false, msg: "登录失效，请重新登录", code: 401 };
                }
            }
        })
    }
}

module.exports = check;